﻿// Copyright (C) 2012 Kim Jensen, TaskJunction.com
// Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TaskJunctionLib.Model;

namespace TaskJunctionLib.Mapping.JSON
{
    public class TaskFilterMapper : JSONMapper<TaskFilter>
    {
        public override void deserializeFromJSON(System.Json.JsonValue jsonObject, TaskFilter obj)
        {
            int ownerUserId;
            obj.Search = jsonObject.ValueOrDefault("search").ReadAs<string>(null);
            ownerUserId = jsonObject.ValueOrDefault("owner_user_id").ReadAs<int>(0);
            obj.OwnerUserId = (ownerUserId != 0) ? (int?)ownerUserId : null;
            obj.TaskStatusIds.Clear();
            for (var i = 1; i <= 5; i++)
            {
                if (jsonObject.ValueOrDefault("task_status_" + i).ReadAs<int>(0) != 0)
                    obj.TaskStatusIds.Add(i);
            }
            if (obj.TaskStatusIds.Count == 0)
                obj.TaskStatusIds.AddRange(new int []{1, 2, 3});
        }

        public override void serializeToJSON(System.Json.JsonValue jsonObject, TaskFilter obj)
        {
            var statusIds = new int[5];
            var statuses = obj.TaskStatusIds;
            for (int i = 0; i < statuses.Count; i++)
            {
                int statusId = statuses[i];
                if (statusId > 0 && statusId <= statusIds.Length)
                    statusIds[statusId - 1] = 1;
            }
            for (int i = 0; i < statusIds.Length; i++)
                jsonObject["task_status_" + (i + 1)] = statusIds[i];
            jsonObject["search"] = obj.Search;
            jsonObject["owner_user_id"] = obj.OwnerUserId;
        }

        protected override string JSONName()
        {
            return "task_filter";
        }
    }
}
